﻿using Dapper;
using HBase;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hCommand {
    public class TransUtil {

        static  public CoreTask getCoreTask(Sw sw, long taskId) {
            string sql = @"select * from Core_task where id=@taskId ";
            List<CoreTask> list = sw.query<CoreTask>(sql, new {
                taskId
            });
            if (list.Count < 1) {
                throw new Exception(taskId + " 任务不存在!");
            }
            return list[0];
        }
        static public CoreWhGroup updateMoveGroup(Sw sw, long areaId, int moveGroup, int craneId) {
            if (!BaseConfig.islocGroup) {
                return null;
            }
            CoreWhGroup group = getCoreWhGroup(sw, areaId, moveGroup);
            CoreWhGroup data = statAreaGroupData(sw, areaId, moveGroup);
            group.maxStock = data.maxStock;
            group.countStock = data.countStock;
            group.countIn = data.countIn;
            group.countOut = data.countOut;

            if (group.id == 0) {
                if (craneId > 0) {
                    group.id = I18nConfig.getGroupId(sw, moveGroup);
                    group.craneId = (byte)craneId;
                    sw.insert(group);
                }

            } else {
                int begin = (int)CoreTaskParamStatus.待执行;
                int end = (int)CoreTaskParamStatus.执行结束;
                String sql = @"  SELECT count(*) FROM core_task_param  where des = @des  and (type<>9 && status between " + begin + "  and " + end + ")";
                group.countIning = sw.queryUnique<int>(sql, new { des = group.id });
                sw.update(group);
            }
            return group;
        }

        static CoreWhGroup statAreaGroupData(Sw sw, long areaId, long moveGroup) {
            String sql = @" select sum(max_stock) max_Stock,sum(count_stock) count_Stock,
                        sum(Count_out) count_out,sum(count_in) count_In,sum(count_outin) count_outin
                            from core_wh_loc 
                            where area_Id = @areaId and move_group=@moveGroup  and Active_Status in (0,1,2)";
            CoreWhGroup res = sw.queryUnique<CoreWhGroup>(sql, new { areaId, moveGroup });
            return res;
        }
        static CoreWhGroup getCoreWhGroup(Sw sw, long areaId, int moveGroup) {
            string sql1 = "select * from   Core_Wh_Group where area_Id=@areaId and loc_group=@moveGroup";
            CoreWhGroup group = sw.queryUnique<CoreWhGroup>(sql1, new { areaId, moveGroup });
            if (group == null) {
                group = new CoreWhGroup();
                group.areaId = areaId;
                group.locGroup = moveGroup;
            }
            return group;
        }

    }
}
